package cn.stu.cms.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.stu.cms.dto.PageDto;
import cn.stu.cms.mapper.AnnouncementMapper;
import cn.stu.cms.pojo.Announcement;
import cn.stu.cms.service.AnnouncementService;
import cn.stu.cms.util.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import static cn.stu.cms.common.CommonConstants.*;

/**
 * 公告服务IMPL
 * 公告表服务层
 *
 * @author gh
 * @date 2023/09/19
 */
@Service
public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Announcement> implements AnnouncementService {


    /**
     * 添加
     *
     * @param announcement 公告
     * @return {@link R}<{@link Boolean}>
     */
    @Override
    public R<Boolean> add(Announcement announcement) {
        baseMapper.insert(announcement);
        return R.ok(SAVE_OK_MSG);
    }

    /**
     * 删除
     *
     * @param id ID
     * @return {@link R}<{@link Boolean}>
     */
    @Override
    public R<Boolean> delete(Long id) {
        boolean exists = lambdaQuery().eq(Announcement::getAnnouncementId, id).exists();
        if (!exists) {
            return R.failed(ID_ERROR);
        }
        baseMapper.deleteById(id);
        return R.ok(DEL_OK_MSG);
    }

    /**
     * 编辑
     *
     * @param announcement 公告
     * @return {@link R}<{@link Boolean}>
     */
    @Override
    public R<Boolean> edit(Announcement announcement) {
        boolean exists = lambdaQuery().eq(Announcement::getAnnouncementId, announcement.getAnnouncementId()).exists();
        if (!exists) {
            return R.failed(ID_ERROR);
        }
        baseMapper.updateById(announcement);
        return R.ok(EDIT_OK_MSG);
    }

    /**
     * 获取页面
     *
     * @param pageDto      页数到页
     * @param announcement 公告
     * @return {@link R}<{@link Page}<{@link Announcement}>>
     */
    @Override
    public R<Page<Announcement>> getPage(PageDto<Announcement> pageDto, Announcement announcement) {
        lambdaQuery().like(StrUtil.isNotBlank(announcement.getTitle()), Announcement::getTitle, announcement.getTitle())
                .orderByDesc(Announcement::getCreateTime)
                .page(pageDto);
        return R.ok(pageDto, GET_INFO_OK);
    }
}
